package com.liuzhu.chaoshikucungunli;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputEditText;
import com.liuzhu.chaoshikucungunli.db.UserDao;
import com.liuzhu.chaoshikucungunli.model.User;

public class RegisterActivity extends AppCompatActivity {
    private TextInputEditText usernameEdit;
    private TextInputEditText passwordEdit;
    private TextInputEditText confirmPasswordEdit;
    private TextInputEditText phoneEdit;
    private UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        userDao = new UserDao(this);
    }

    private void initViews() {
        usernameEdit = findViewById(R.id.username_edit);
        passwordEdit = findViewById(R.id.password_edit);
        confirmPasswordEdit = findViewById(R.id.confirm_password_edit);
        phoneEdit = findViewById(R.id.phone_edit);

        findViewById(R.id.btn_back).setOnClickListener(v -> finish());
        findViewById(R.id.btn_register).setOnClickListener(v -> attemptRegister());
    }

    private void attemptRegister() {
        // 获取输入内容
        String username = usernameEdit.getText().toString().trim();
        String password = passwordEdit.getText().toString().trim();
        String confirmPassword = confirmPasswordEdit.getText().toString().trim();
        String phone = phoneEdit.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(username)) {
            usernameEdit.setError("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            passwordEdit.setError("请输入密码");
            return;
        }
        if (TextUtils.isEmpty(confirmPassword)) {
            confirmPasswordEdit.setError("请确认密码");
            return;
        }
        if (!password.equals(confirmPassword)) {
            confirmPasswordEdit.setError("两次输入的密码不一致");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            phoneEdit.setError("请输入手机号");
            return;
        }
        if (userDao.getUserByUsername(username) != null) {
            usernameEdit.setError("用户名已存在");
            return;
        }

        // 创建新用户
        User user = new User(username, password, phone,"员工","快乐每一天货物公司");
        long userId = userDao.addUser(user);

        if (userId > 0) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "注册失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }


} 